/**
 * @CDManager.as
 * 
 * @author sodaChen mail:sujun10#21cn.com
 * @version 1.0
 * <br>Copyright (C), 2012 ASFrame.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:LLModule
 * <br>Date:2014-12-2
 */
package com.asframe.cd
{
	import com.asframe.collections.maps.HashMap;

	/**
	 * CD管理器
	 * @author sodaChen
	 * Date:2014-12-2
	 */
	public class CDManager
	{
		private static var instance:CDManager;
		
		
		private var cdMap:HashMap = new HashMap();
		
		public static function getInstance():CDManager
		{
			if(instance == null)
			{
				instance = new CDManager();
			}
			return instance;
		}
		
		public function clear():void
		{
			for each (var cdHandler:CDHandler in cdMap.getContainer()) 
			{
				cdHandler.stopCD();
			}
			cdMap.clear();
		}
		/**
		 * 注册一个CD显示对象 
		 * @param id
		 * @param cd
		 * 
		 */		
		public function registerCD(id:String,cd:ICD):void
		{
			var cdHandler:CDHandler = new CDHandler();
			cdHandler.cd = cd;
			cdMap.put(id,cdHandler);
		}
		/**
		 * 取消一个CD显示对象 
		 * @param id
		 * 
		 */		
		public function unRegisterCD(id:String):void
		{
			var cdHandler:CDHandler = cdMap.remove(id);
			if(cdHandler == null)
			{
				throw new Error(id + "CD显示操作错误，没有注册对应的CD操作对象" );
			}
			cdHandler.stopCD();
		}
		/**
		 * 对已经存在的CD对象进行CD显示 
		 * @param id
		 * @param overTime
		 * 
		 */		
		public function showCD(id:String,overTime:int):void
		{
			var cdHandler:CDHandler = cdMap.get(id);
			if(cdHandler == null)
			{
				throw new Error(id + "CD显示操作错误，没有注册对应的CD操作对象" );
			}
			cdHandler.overTime = overTime;
			cdHandler.startCD(overTime);
		}
		public function closeCD(id:String):void
		{
			var cdHandler:CDHandler = cdMap.get(id);
			if(cdHandler == null)
			{
				throw new Error(id + "CD显示操作错误，没有注册对应的CD操作对象" );
			}
			cdHandler.stopCD();
		}
	}
}
import com.asframe.cd.ICD;
//import com.asframe.managers.TimerManager;
import com.asframe.mgr.TimeMgr;

import flash.utils.getTimer;

class CDHandler
{
	/** 是否正在跑动 **/
	public var isRuning:Boolean;
	public var overTime:int;
	public var lastTime:int;
	public var cd:ICD;
	
	public function startCD(overTime:int):void
	{
		this.overTime = overTime;
		lastTime = getTimer();
		cd.startCD(lastTime);
		isRuning = true;
		//启动倒计时
		TimeMgr.addDelay(1000,onTickCD);
	}
	public function stopCD():void
	{
		if(isRuning)
		{
			isRuning = false;
			TimeMgr.removeDelay(onTickCD);
			cd.timeOver();
		}
	}
	private function onTickCD():void
	{
		lastTime = overTime - getTimer();
		if(lastTime > 0)
		{
			cd.update(lastTime);
		}
		else
		{
			stopCD();
		}
	}
}